//
//  ECManager_Pay.m
//  Edu_iOS2018
//
//  Created by yanyan on 2018/1/29.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECManager_Pay.h"
#import "CYUIAlertView.h"
#import "CYDataHelper.h"
#import <AlipaySDK/AlipaySDK.h>
@implementation ECManager_Pay
+ (instancetype)sharedInstance
{
    static ECManager_Pay *access_weixinPay = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        access_weixinPay = [[self alloc]init];
    });
    return access_weixinPay;
}
- (void)payOrder:(id)order finished:(void (^)(id))finished
{
    //https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12&index=2
    if ([CYDataHelper isNull:[order valueForKey:@"prepayid"]] || [CYDataHelper isNull:[order valueForKey:@"partnerid"]]) {
        [MBProgressHUD showErrorMessage:@"微信支付信息有误"];
        return;
    }
    PayReq *payRequest = [[PayReq alloc]init];

//    payRequest.partnerId = [order valueForKey:@"mch_id"];//商户号id
//    payRequest.prepayId = [order valueForKey:@"prepay_id"];//预支付交易会话ID
//    payRequest.package = @"Sign=WXPay";//这是拓展字段-固定值
//    payRequest.nonceStr = [order valueForKey:@"nonce_str"];//-nonce_str-随机字符串
////    payRequest.timeStamp = [[order valueForKey:@"timestamp"] intValue];//时间戳
//    payRequest.sign = [order valueForKey:@"sign"];//签名
  
    payRequest.partnerId = [order valueForKey:@"partnerid"];//商户号id
    payRequest.prepayId = [order valueForKey:@"prepayid"];//预支付交易会话ID
    payRequest.package = @"Sign=WXPay";//这是拓展字段-固定值
    payRequest.nonceStr = [order valueForKey:@"noncestr"];//-nonce_str-随机字符串
    payRequest.timeStamp = [[order valueForKey:@"timestamp"] intValue];//时间戳
    payRequest.sign = [order valueForKey:@"sign"];//签名
    self.block_paySuccess = ^(id sender){
        finished(sender);
    };
    if ([WXApi isWXAppInstalled]) {
        [WXApi sendReq:payRequest];
    } else {
        finished(nil);
    }
    /*
     名称    描述    解决方案
     0    成功    展示成功页面
     -1    错误    可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
     -2    用户取消    无需处理。发生场景：用户不支付了，点击取消，返回APP。
     */
}
- (void)payAliOrder:(id)order finished:(void (^)(id))finished
{
    AlipaySDK *alipayManager = [AlipaySDK defaultService];
    [alipayManager payOrder:order fromScheme:@"com.khcm.demo1" callback:^(NSDictionary *resultDic) {
        DLog(@"支付宝支付结果 ： %@",resultDic);
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([[resultDic valueForKey:@"resultStatus"]integerValue] == 9000) {
                [[NSNotificationCenter defaultCenter]postNotificationName:kNotifactionAlipayPaySuccess object:nil];
            } else {
                [[NSNotificationCenter defaultCenter]postNotificationName:kNotifactionAlipayPayFail object:nil];
            }
        });
       
        DLog(@"支付finished： %@",resultDic);

        finished(resultDic);
        
    }];
}
#pragma mark  -  weixin 支付代理-
-(void)onReq:(BaseReq *)req
{
    DLog(@"%@",req.description);
}
-(void)onResp:(BaseResp *)resp
{
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        /*
         ErrCode ERR_OK = 0(用户同意)
         ERR_AUTH_DENIED = -4（用户拒绝授权）
         ERR_USER_CANCEL = -2（用户取消）
         code    用户换取access_token的code，仅在ErrCode为0时有效
         state   第三方程序发送时用来标识其请求的唯一性的标志，由第三方程序调用sendReq时传入，由微信终端回传，state字符串长度不能超过1K
         lang    微信客户端当前语言
         country 微信用户当前国家信息
         */
        SendAuthResp *response = (SendAuthResp *)resp;
        if (response.errCode == 0) {
            NSString *code = response.code;
        }
        
    } else if ([resp isKindOfClass:[PayResp class]]) {
        // 支付完回调
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *strMsg = @"支付结果";
        
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付成功！";
                break;
            case WXErrCodeUserCancel:
                strMsg = @"支付取消";
                break;
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                break;
        }

        WeakSelf(weakSelf);
        if (weakSelf.block_paySuccess) {
            weakSelf.block_paySuccess(resp);
        }

    }
    
}
@end
